package com.chunfeng.lerunapplication.fragement;

import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.chunfeng.lerunapplication.R;
import com.chunfeng.lerunapplication.api.OrderApi;
import com.chunfeng.lerunapplication.dialog.UpdateOrderDialog;
import com.chunfeng.lerunapplication.entity.JsonRequest;
import com.chunfeng.lerunapplication.entity.Orders;
import com.chunfeng.lerunapplication.list.ListAdapt;
import com.chunfeng.lerunapplication.spinner.SelectAdapt;
import com.chunfeng.lerunapplication.utils.CacheUtils;
import com.chunfeng.lerunapplication.utils.JsonSerializeUtils;
import com.chunfeng.lerunapplication.utils.TokenUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 订单页
 */
public class OrderFragment extends Fragment implements View.OnClickListener {
    /**
     * 选项框
     */
    private Spinner spinnerStatus;
    /**
     * 新增按钮
     */
    private Button insertButton;
    /**
     * 列表组件
     */
    private RecyclerView recyclerView;
    /**
     * 数据
     */
    private List<Orders> dataList;
    /**
     * 接口
     */
    private OrderApi orderApi;
    /**
     * 选项框
     */
    private Map<Integer, Object> selectMap = new HashMap<Integer, Object>() {
        /**
         * 序列化字段
         */
        private static final long serialVersionUID = -5909628475341288940L;

        {
            put(0, "未完成");
            put(1, "已完成");
            put(2, "未知错误");
        }
    };
    /**
     * 用户ID
     */
    private Integer userId;

    /**
     * 创建时触发
     *
     * @param savedInstanceState 视图状态
     */
    @Override
    public void onCreate(@Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        orderApi = new OrderApi(getContext());
    }

    /**
     * 初始化选项框
     */
    private void initSelect() {
        spinnerStatus.setAdapter(new SelectAdapt(selectMap));
        //点击时
        spinnerStatus.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            /**
             * 当选中项时
             * @param parent 父容器
             * @param view 当前点击的视图
             * @param position 索引
             * @param id 选中的ID
             */
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                initData(position);
            }

            /**
             * 未选中时
             * @param parent 父容器
             */
            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }

    /**
     * 初始化数据
     */
    private void initData(Integer status) {
        String token = new CacheUtils(getContext()).getValue("token");
        if (token.isEmpty()) {
            return;
        }
        userId = TokenUtils.checkToken(token, Integer.class);
        if (userId == null) {
            return;
        }
        Orders orders = new Orders();
        orders.setUser(userId);
        orders.setStatus(status);
        JsonRequest<List<Orders>> jsonRequest = orderApi.lookOrdersByCondition(orders);
        if (!jsonRequest.getSuccess()) {
            Log.w("Exception", jsonRequest.getMessage());
            return;
        }
        //二次转换
        dataList = JsonSerializeUtils.serializeList(jsonRequest.getData(), Orders.class);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        recyclerView.setAdapter(new ListAdapt(dataList));
    }

    /**
     * 绑定布局文件
     *
     * @param inflater           视图反射对象
     * @param container          父容器
     * @param savedInstanceState 状态
     * @return 视图对象
     */
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_order, container, false);
        spinnerStatus = view.findViewById(R.id.Spinner_Status);
        insertButton = view.findViewById(R.id.InsertOrder_Button);
        recyclerView = view.findViewById(R.id.Order_List);
        insertButton.setOnClickListener(this);
        initSelect();
        initData(0);
        return view;
    }

    /**
     * 点击事件
     *
     * @param v 点击的元素
     */
    @Override
    public void onClick(View v) {
        int id = v.getId();
        //新增订单
        if (id == R.id.InsertOrder_Button) {
            UpdateOrderDialog orderDialog = new UpdateOrderDialog(getContext())
                    .setTitle("新增订单")
                    .setDescription("")
                    .setOnSubmitBtnClickListener(this::insertOneOrder)
                    .setOnCancelBtnClickListener(UpdateOrderDialog::dismiss);
            orderDialog.show();
        }
    }

    /**
     * 新增订单
     *
     * @param updateOrderDialog 弹窗对象
     */
    private void insertOneOrder(UpdateOrderDialog updateOrderDialog) {
        //获取弹窗的信息
        String description = updateOrderDialog.descriptionView().getText().toString();
        if (description.isEmpty()) {
            return;
        }
        Orders orders = new Orders();
        orders.setUser(userId);
        orders.setDescription(description);
        JsonRequest<Integer> jsonRequest = orderApi.insertOneOrder(orders);
        if (!jsonRequest.getSuccess()) {
            Toast.makeText(getContext(), jsonRequest.getMessage(), Toast.LENGTH_SHORT).show();
            return;
        }
        Toast.makeText(getContext(), "新增订单成功!", Toast.LENGTH_SHORT).show();
        initData(0);
    }
}